package com.smh.ui;

import com.smh.pojo.GameInfo;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;
import java.util.Random;

public class GameJFrame extends JFrame implements KeyListener, MouseListener, ActionListener {
    //这个界面就是游戏主界面

    //创建二维数组
    int[][] data = new int[4][4];
    int[][] win = new int[][]{
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 0}
    };

    Random random = new Random();
    //记录空白方块在二维数组中的位置
    int x, y;
    //记录显示图片的路径
    String path = "pintugame\\image\\animal\\animal1\\";

    //定义计步变量
    int count = 0;

    //选项下的条目对象(放在这里是为了让事件监听访问到)
    JMenuItem beauty = new JMenuItem("美女");
    JMenuItem animal = new JMenuItem("动物");
    JMenuItem sport = new JMenuItem("运动");

    JMenuItem replayItem = new JMenuItem("重新游戏");
    JMenuItem reLoginItem = new JMenuItem("重新登录");
    JMenuItem closeItem = new JMenuItem("关闭游戏");

    JMenuItem accountItem = new JMenuItem("公众号");
    JMenu saveJMenu = new JMenu("存档");
    JMenu loadJMenu = new JMenu("读档");

    JMenuItem saveItem0 = new JMenuItem("存档0(空)");
    JMenuItem saveItem1 = new JMenuItem("存档1(空)");
    JMenuItem saveItem2 = new JMenuItem("存档2(空)");
    JMenuItem saveItem3 = new JMenuItem("存档3(空)");
    JMenuItem saveItem4 = new JMenuItem("存档4(空)");

    JMenuItem loadItem0 = new JMenuItem("读档0(空)");
    JMenuItem loadItem1 = new JMenuItem("读档1(空)");
    JMenuItem loadItem2 = new JMenuItem("读档2(空)");
    JMenuItem loadItem3 = new JMenuItem("读档3(空)");
    JMenuItem loadItem4 = new JMenuItem("读档4(空)");

    public GameJFrame() throws HeadlessException {
        //初始化界面
        initJFrame();
        //初始化菜单
        initJMenu();
        //初始化数据
        initData();
        //初始化图片
        initImage();


        this.setVisible(true);//显示界面
    }

    private void getGameInfo() {
        File file = new File("pintugame\\file\\save");
        File[] files = file.listFiles();
        for (File file1 : files) {
            int index = file1.getName().charAt(4) - '0';
            GameInfo gameInfo = null;
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file1));
                gameInfo = (GameInfo) ois.readObject();
                ois.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            saveJMenu.getItem(index).setText("存档" + index + "(" + gameInfo.getStep() + "步)");
            loadJMenu.getItem(index).setText("读档" + index + "(" + gameInfo.getStep() + "步)");
        }
    }

    private void initData() {
        count = 0;
        int[] tempArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        for (int i = 0; i < tempArr.length; i++) {
            int index = random.nextInt(tempArr.length);
            int temp = tempArr[i];
            tempArr[i] = tempArr[index];
            tempArr[index] = temp;
        }

        for (int i = 0; i < tempArr.length; i++) {
            data[i / 4][i % 4] = tempArr[i];
        }
    }

    private void initImage() {
        //清空图片
        this.getContentPane().removeAll();
        //判断胜利
        if (victory()) {
            System.out.println("胜利");
            JLabel victory = new JLabel(new ImageIcon("pintugame\\image\\win.png"));
            victory.setBounds(203, 283, 197, 73);
            this.getContentPane().add(victory);
            this.getContentPane().repaint();
        }
        //计步显示
        JLabel stepCount = new JLabel("步数" + count);
        stepCount.setBounds(50, 30, 100, 20);
        this.getContentPane().add(stepCount);
        //显示图片
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                //创建ImageIcon对象
                ImageIcon imageIcon = new ImageIcon(path + data[i][j] + ".jpg");
                //创建JLabel对象
                JLabel jLabel = new JLabel(imageIcon);
                //指定图片位置
                jLabel.setBounds(j * 105 + 83, i * 105 + 134, 105, 105);
                //添加边框
                jLabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
                //把容器添加到界面中
                //this.add(jLabel);
                this.getContentPane().add(jLabel);
                //拿到0的位置
                if (data[i][j] == 0) {
                    x = i;
                    y = j;
                }
            }
        }
        //添加背景图片
        JLabel background = new JLabel(new ImageIcon("pintugame\\image\\background.png"));
        background.setBounds(40, 40, 508, 560);
        this.getContentPane().add(background);

        //刷新页面
        this.getContentPane().repaint();

    }

    private void initJMenu() {
        //初始化菜单
        JMenuBar jMenuBar = new JMenuBar();

        //菜单选项
        JMenu functionJMenu = new JMenu("功能");
        JMenu aboutJmenu = new JMenu("关于我们");
        JMenu selectJmenu = new JMenu("切换图片");


        //绑定事件
        beauty.addActionListener(this);
        animal.addActionListener(this);
        sport.addActionListener(this);
        replayItem.addActionListener(this);
        reLoginItem.addActionListener(this);
        closeItem.addActionListener(this);
        accountItem.addActionListener(this);
        saveItem0.addActionListener(this);
        saveItem1.addActionListener(this);
        saveItem2.addActionListener(this);
        saveItem3.addActionListener(this);
        saveItem4.addActionListener(this);
        loadItem0.addActionListener(this);
        loadItem1.addActionListener(this);
        loadItem2.addActionListener(this);
        loadItem3.addActionListener(this);
        loadItem4.addActionListener(this);

        //添加
        selectJmenu.add(beauty);
        selectJmenu.add(animal);
        selectJmenu.add(sport);

        //把5个存档，添加到saveJMenu中
        saveJMenu.add(saveItem0);
        saveJMenu.add(saveItem1);
        saveJMenu.add(saveItem2);
        saveJMenu.add(saveItem3);
        saveJMenu.add(saveItem4);

        //把5个读档，添加到loadJMenu中
        loadJMenu.add(loadItem0);
        loadJMenu.add(loadItem1);
        loadJMenu.add(loadItem2);
        loadJMenu.add(loadItem3);
        loadJMenu.add(loadItem4);

        functionJMenu.add(selectJmenu);
        functionJMenu.add(replayItem);
        functionJMenu.add(reLoginItem);
        functionJMenu.add(closeItem);
        functionJMenu.add(loadJMenu);
        functionJMenu.add(saveJMenu);

        aboutJmenu.add(accountItem);

        jMenuBar.add(functionJMenu);
        jMenuBar.add(aboutJmenu);

        //读取本地存档信息
        getGameInfo();

        //设置菜单
        this.setJMenuBar(jMenuBar);
    }

    private void initJFrame() {
        this.setSize(603, 680);//设置界面大小
        //设置页面标题
        this.setTitle("拼图单机版v1.0");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面剧中
        this.setLocationRelativeTo(null);
        //设置游戏关闭方式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认居中放置
        this.setLayout(null);
        //给页面添加监听事件
        this.addKeyListener(this);

    }


    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {//按下
        if (victory()) {
            return;
        }//关闭方法
        int code = e.getKeyCode();
        if (code == 65) {
//            System.out.println(code);
            //显示完整图片
            this.getContentPane().removeAll();
            JLabel all = new JLabel(new ImageIcon(path + "all.jpg"));
            all.setBounds(83, 134, 420, 420);
            //背景图片
            JLabel background = new JLabel(new ImageIcon("pintugame\\image\\background.png"));
            background.setBounds(40, 40, 508, 560);

            this.getContentPane().add(all);
            this.getContentPane().add(background);
            //刷新页面
            this.getContentPane().repaint();
        }
    }

    //移动
    @Override
    public void keyReleased(KeyEvent e) {
        //松开
        //对上下左右进行判断
        if (victory()) {
            return;
        }//关闭方法

        int code = e.getKeyCode();
        if (code == 37) {
            System.out.println("左移");
            if (y + 1 < 4) {
                data[x][y] = data[x][y + 1];
                data[x][y + 1] = 0;
                y++;
                count++;
                initImage();
            }
        } else if (code == 38) {
            System.out.println("上移");
            if (x + 1 < 4) {
                data[x][y] = data[x + 1][y];
                data[x + 1][y] = 0;
                x++;
                count++;
                initImage();
            }

        } else if (code == 39) {
            System.out.println("右移");
            if (y - 1 >= 0) {
                data[x][y] = data[x][y - 1];
                data[x][y - 1] = 0;
                y--;
                count++;
                initImage();
            }
        } else if (code == 40) {
            System.out.println("下移");
            if (x - 1 >= 0) {
                data[x][y] = data[x - 1][y];
                data[x - 1][y] = 0;
                x--;
                count++;
                initImage();
            }
        } else if (code == 65) {
            initImage();
        } else if (code == (int) 'W') {
            //System.out.println(code);
            data = new int[][]{
                    {1, 2, 3, 4},
                    {5, 6, 7, 8},
                    {9, 10, 11, 12},
                    {13, 14, 15, 0}
            };
            initImage();
        }
    }

    //判断是否胜利
    public boolean victory() {
        for (int i = 0; i < win.length; i++) {
            for (int j = 0; j < win[i].length; j++) {
                if (data[i][j] == win[i][j]) {
                    continue;
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void mouseClicked(MouseEvent e) {//单击

    }

    @Override
    public void mousePressed(MouseEvent e) {//按下

    }

    @Override
    public void mouseReleased(MouseEvent e) {//松开

    }

    @Override
    public void mouseEntered(MouseEvent e) {//移入

    }

    @Override
    public void mouseExited(MouseEvent e) {//移除

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //获取点击的条目对象
        Object obj = e.getSource();

        if (obj == replayItem) {//重新开始
            count = 0;
            initData();
            initImage();

        } else if (obj == reLoginItem) {//重新登录
            this.setVisible(false);
            try {
                new LoginJFrame();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

        } else if (obj == closeItem) {//关闭
            System.exit(0);
        } else if (obj == accountItem) {//二维码
            //开辟弹框
            JDialog jDialog = new JDialog();
            //
            Properties pro = new Properties();
            try {
                FileInputStream fis = new FileInputStream("pintugame\\game.properties");
                pro.load(fis);
                fis.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            //创建jlabel容器管理图片
            JLabel jLabel = new JLabel(new ImageIcon((String) pro.get("account")));
            //shehzi位置()是相对与弹框的位置
            jLabel.setBounds(0, 0, 258, 258);
            //将图片添加到弹框
            jDialog.getContentPane().add(jLabel);

            jDialog.setSize(344, 344);
            //始终在最顶层
            jDialog.setAlwaysOnTop(true);
            //剧中
            jDialog.setLocationRelativeTo(null);
            //弹窗不关闭,无法操作其他事件
            jDialog.setModal(true);
            //
            jDialog.setVisible(true);
        } else if (obj == beauty) {//换美女图片
            int index = random.nextInt(13) + 1;
            path = "pintugame\\image\\girl\\girl" + index + "\\";
            initData();
            initImage();
        } else if (obj == animal) {//换动物图片
            int index = random.nextInt(8) + 1;
            path = "pintugame\\image\\animal\\animal" + index + "\\";
            initData();
            initImage();
        } else if (obj == sport) {//换运动图片
            int index = random.nextInt(10) + 1;
            path = "pintugame\\image\\sport\\sport" + index + "\\";
            initData();
            initImage();
        } else if (obj == saveItem0 || obj == saveItem1 || obj == saveItem2 || obj == saveItem3 || obj == saveItem4) {
            JMenuItem item = (JMenuItem) obj;
            int index = item.getText().charAt(2) - '0';//得到数字
            System.out.println(index);
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("pintugame\\file\\save\\save" + index + ".data"));
                GameInfo gameInfo = new GameInfo(data, x, y, path, count);
                oos.writeObject(gameInfo);
                oos.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            item.setText("存档" + index + "(" + count + "步)");
            loadJMenu.getItem(index).setText("读档" + index + "(" + count + "步)");


        } else if (obj == loadItem0 || obj == loadItem1 || obj == loadItem2 || obj == loadItem3 || obj == loadItem4) {
            JMenuItem item = (JMenuItem) obj;
            int index = item.getText().charAt(2) - '0';
            GameInfo gameInfo = null;
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("pintugame\\file\\save\\save" + index + ".data"));
                gameInfo = (GameInfo) ois.readObject();
                ois.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            }
            data = gameInfo.getData();
            path = gameInfo.getPath();
            x = gameInfo.getX();
            y = gameInfo.getY();
            count = gameInfo.getStep();

            //刷新页面
            initImage();
        }
    }
}
